package main;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import main.MyAnnotations.Column;
import main.MyAnnotations.ColumnId;

public class ReflectionQuery {
	Class cl;
	Annotation[] a;
	Method[] m;
	Field[] f;
	String className;
	
	public String getAddQuery(Object obj) throws Exception {
		StringBuffer sbNames = new StringBuffer();
		StringBuffer sbValues = new StringBuffer();
		cl = obj.getClass();
		f = cl.getDeclaredFields();
		className = cl.getSimpleName().toString();
		
		for (int i = 0; i<f.length; i++) {
			a = f[i].getAnnotations();
			for(int j = 0; j<a.length; j++) {
				if(a[j].annotationType().equals(ColumnId.class))
					break;
				if(a[j].annotationType().equals(Column.class)) {
					sbNames.append(f[i].getName()+",");
					if(f[i].getType()==String.class)
						sbValues.append("'"+f[i].get(obj).toString()+"',");
					else sbValues.append(f[i].get(obj).toString()+",");
				}
			}
		}
		
		String names = sbNames.toString().substring(0, sbNames.length()-1);
		String values = sbValues.toString().substring(0, sbValues.length()-1 );
		String addQuery = "INSERT INTO "+className+" (" + names +") values (" + values + ")";
		return addQuery;
	}
	
	/*public String getUpdateQuery(Object obj) throws Exception {
		cl = obj.getClass();
		f = cl.getDeclaredFields();
		className = cl.getSimpleName().toString();
		
		String[] sNames = new String[f.length];
		String[] sValues = new String[f.length];
		StringBuffer result = new StringBuffer();
		String id = "";
		int nIndex = 0;
		
		
		for (int i = 0; i<f.length; i++) {
			a = f[i].getAnnotations();
			for(int j = 0; j<a.length; j++) {
				if(a[j].annotationType().equals(ColumnId.class)) {
					id = f[i].getName();
					break;
				}
				if(a[j].annotationType().equals(Column.class)) {
					sNames[nIndex] = f[i].getName();
					if(f[i].getType()==String.class){
						sValues[nIndex] = "'"+f[i].get(obj).toString()+"'";
						nIndex++;
					} else {
						sValues[nIndex] = f[i].get(obj).toString();
						nIndex++;
					}
				}
			}
		}
		String addQuery = "UPDATE "+className + "SET " +;
		return addQuery;
	}*/
	
	public String getSelectQuery(Class cl) {
		String clName = cl.getSimpleName().toString();
		return "SELECT * FROM "+clName;
	}
	
}
